package appUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;

import com.example.jhlibrarys.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import static com.example.jhlibrarys.R.integer.flow_byte;
import static com.example.jhlibrarys.R.integer.one_hundred;
import static constant.ApiConstants.INSTALL_PATH;
import static constant.ApiConstants.STORAGE_PATH;

/**
 * Created by lj on 2017/7/13 0013.
 */

public class VersionUpdate {
    private final Context mContext;
    private ProgressDialog progressDialog;

    public VersionUpdate(Context context) {
        this.mContext = context;
    }

    public void downloadVersion(String url) {
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setTitle(mContext.getString(R.string.downloading));
        progressDialog.setCanceledOnTouchOutside(true);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        new downloadAsyncTask(url).execute();
    }


    /**
     * 获取当前版本号
     */
    public String getCurrentVersion() {
        try {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), PackageManager.SIGNATURE_MATCH);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showShort(R.string.versiona_wrong);
            PayTokenException.getInstance().saveExceptionFile("" +
                    "VersionUpdate getCurrentVersion error: " + e.getMessage());
            return "";
        }
    }

    /**
     * 下载新版本应用
     */
    private class downloadAsyncTask extends AsyncTask<Void, Integer, Integer> {
        private String mUrl;

        private downloadAsyncTask() {
        }

        private downloadAsyncTask(String url) {
            this.mUrl = url;
        }

        @Override
        protected void onPreExecute() {
            progressDialog.show();
        }

        @Override
        protected Integer doInBackground(Void... params) {

            URL url;
            HttpURLConnection connection = null;
            InputStream in = null;
            FileOutputStream out = null;
            try {
                url = new URL(mUrl);
                connection = (HttpURLConnection) url.openConnection();

                in = connection.getInputStream();
                long fileLength = connection.getContentLength();
                File file_path = new File(Environment.getExternalStorageDirectory() + STORAGE_PATH);
                if (!file_path.exists()) {
                    file_path.mkdir();
                }

                out = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + INSTALL_PATH));//为指定的文件路径创建文件输出流
                byte[] buffer = new byte[mContext.getResources().getInteger(flow_byte) * mContext.getResources().getInteger(flow_byte)];
                int len;
                long readLength = mContext.getResources().getInteger(R.integer.zero);

                while ((len = in.read(buffer)) != mContext.getResources().getInteger(R.integer.minus_one)) {

                    out.write(buffer, mContext.getResources().getInteger(R.integer.zero), len);//从buffer的第0位开始读取len长度的字节到输出流
                    readLength += len;

                    int curProgress = (int) (((float) readLength / fileLength) * mContext.getResources().getInteger(one_hundred));

                    publishProgress(curProgress);

                    if (readLength >= fileLength) {

                        break;
                    }
                }
                out.flush();
                return mContext.getResources().getInteger(R.integer.one);

            } catch (Exception e) {
                e.printStackTrace();
                PayTokenException.getInstance().saveExceptionFile("" +
                        "VersionUpdate doInBackground error: " + e.getMessage());
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        PayTokenException.getInstance().saveExceptionFile("" +
                                "VersionUpdate doInBackground IOException out: " + e.getMessage());
                    }
                }

                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        PayTokenException.getInstance().saveExceptionFile("" +
                                "VersionUpdate doInBackground IOException in: " + e.getMessage());
                    }
                }

                if (connection != null) {
                    connection.disconnect();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            progressDialog.setProgress(values[mContext.getResources().getInteger(R.integer.zero)]);
        }

        @Override
        protected void onPostExecute(Integer integer) {

            progressDialog.dismiss();//关闭进度条
            //安装应用
            installApp();
        }

        /**
         * 安装新版本应用
         */
        private void installApp() {
            File appFile = new File(Environment.getExternalStorageDirectory() + INSTALL_PATH);
            if (!appFile.exists()) {
                return;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri data;
            // 判断版本大于等于7.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                data = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileProvider", appFile);
                // 给目标应用一个临时授权
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                data = Uri.fromFile(appFile);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(data, "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        }
    }
}
